package com.ifnk.portaljava.dapWeb.dapweb;
/**
 * <p>Title: 处理rawdata包类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */
/*
 * 维护同一个CDR里的多个PACKET之间的对应关系，
 * 如果后台有重复发送的情况在这里做判断，
 * 不需要做后续的处理，也不需要往界面送。
 */

import com.ifnk.portaljava.dapWeb.common.Util;
import com.ifnk.portaljava.dapWeb.pacp.Pacp_file_header;
import com.ifnk.portaljava.dapWeb.socket.ClientProperty;
import com.ifnk.portaljava.hlyt.test.Tshark;
import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.*;

public class CDRPacket {
	private Log loger = LogFactory.getLog(CDRPacket.class);
	private static String tshark;
	private static String pcapfilepath;
	@SuppressWarnings("unused")
	private static String psml;
	private static String pdml;
	private static String pcapNativeFile;
	private static String fileSeparator;
	private SignallingPacket signallingPacket = new SignallingPacket();
	private CDRBean cdrBean = new CDRBean();
	static {
		Locale locale = Locale.ENGLISH;
		ResourceBundle localResource = ResourceBundle.getBundle("Socket", locale);
		tshark = localResource.getString("tshark");
		pcapfilepath = localResource.getString("pacpfilepath");
		psml = localResource.getString("psml");
		pdml = localResource.getString("pdml");
		pcapNativeFile = localResource.getString("pcapNativeFile");
		fileSeparator = localResource.getString("separator");
	}

	public CDRBean processCDRPacket(Command command, ClientProperty cp) {
		
		CDRBean cdrBean = null;
		Map<String, List<Integer>> cdrPackets = cp.getCdrPackets();
		List<Integer> list = null;
		String cdrKey = command.getSvrId() + "_" + command.getCdrId() + "_" + command.getChar_protocol() + "_" + command.getTs_s();
		if (cdrPackets.containsKey(cdrKey)) {
			list = cdrPackets.get(cdrKey);

			if (list.contains(command.getSequenceNo())) {
				return cdrBean;
			} else {
				list.add(command.getSequenceNo());
			}

		} else {
			list = new ArrayList<Integer>();
			list.add(command.getSequenceNo());
			cdrPackets.put(cdrKey, list);
		}

		// 处理pkt
		String fileName = pcapNativeFile + cp.getRequestDateFromProxyId()
				+ fileSeparator + cdrKey;

		String filePath = fileName + fileSeparator + new java.text.DecimalFormat("000000").format(command.getSequenceNo())
				+ ".dat";
		try {
			savePacketToNativeFile(fileName, filePath, command.getPkt(), false);
			cdrBean = processPKT(command);
//			cp.cdrPktInfoMap.get(cdrKey).setSummaryDecode(false);
//			cp.cdrPktInfoMap.get(cdrKey).setDetailedDecode(false);
			cp.cdrPktInfoMap.get(cdrKey).setPktIndex(cp.cdrPktInfoMap.get(cdrKey).getPktIndex() + 1);
//			String filename = pcapfilepath + "summary" + File.separator + sessionId
//			+ File.separator + cdrKey;
//			new File(filename).delete();
			System.out.println("command.getCdrEndFlag()" + command.getCdrEndFlag());
			if(command.getCdrEndFlag() == 1) {
				cp.cdrPktInfoMap.get(cdrKey).setEndFlag(true);
			}
		} catch (Exception e) {
			loger.error("WebServer Exception " + e.toString());
			e.printStackTrace();
		}
		return cdrBean;
	}

	private CDRBean processPKT(Command command) throws Exception {
//		int complementCode = (((command.getPkt()[4] & 0xf3) << 8 | command
//				.getPkt()[5]) == 0x04) ? 2 : 0;
		byte[] packet;
		String key = command.getSvrId() + "_" + command.getCdrId() + "_" + command.getChar_protocol() + "_" + command.getTs_s();
		String filename = pcapfilepath + fileSeparator + "summary" + fileSeparator + command.getSessionId() + fileSeparator + key;
		String filepath = filename + fileSeparator + key +".pcap";
		if(new File(filepath).exists()) {
			packet = signallingPacket.TransformToDataPacket(command.getPkt());
		} else {
			packet = signallingPacket.convertPacketToPcap(command.getPkt());
		}
		savePacketToNativeFile(filename, filepath, packet, true);
//		System.out.println("append " + command.getSequenceNo());
		
		String fileName = pcapfilepath + fileSeparator + "detailed" + fileSeparator + command.getSessionId() + fileSeparator + key;
		@SuppressWarnings("unused")
		boolean flag = false;
		flag = Tshark.deleteFile(new File(fileName));
		return cdrBean;
	}

	public CDRBean processPKT(String clientid, String cdrKey, String SequenceNo, boolean decodeToXML)
			throws Exception {
		File file = new File(pcapNativeFile + clientid + fileSeparator + cdrKey
				+ fileSeparator + SequenceNo + ".dat");
		FileInputStream in = new FileInputStream(file);
		byte[] packet = new byte[(int) file.length()];
		in.read(packet);
		in.close();
		String filename = pcapfilepath + fileSeparator + "detailed" + fileSeparator + clientid + fileSeparator + cdrKey;
		file = new File(filename);
		if (!file.exists())
			file.mkdirs();
		String filepath = filename + fileSeparator + SequenceNo + ".pcap";
		byte[] pcapPacket = signallingPacket.convertPacketToPcap(packet);
		savePKTtoFile(filepath, pcapPacket, false);
		String tsharkcmd = tshark + " -r" + filepath + " " + pdml;
		int complementCode = (((packet[4] & 0xf3) << 8 | packet[5]) == 0x04) ? 2 : 0;
		byte[] data = new byte[packet.length - (20 + complementCode)];
		System.arraycopy(packet, 20 + complementCode, data, 0, packet.length
				- (20 + complementCode));
		cdrBean = signallingPacket.informationDecoding(tsharkcmd, filepath,
				cdrBean, data, true, decodeToXML);
		return cdrBean;
	}

	public void savePKTtoFile(String filepath, byte[] pcapPacket, boolean append)
			throws IOException {
		DataOutputStream output = new DataOutputStream(new FileOutputStream(
				new File(filepath), append));
		output.write(pcapPacket);
		output.flush();
		output.close();
	}

	public void savePacketToNativeFile(String filename, String filepath,
			byte[] packet, boolean append) throws IOException {
		File file = new File(filename);
		if (!file.exists()) {
			file.mkdirs();
		}
		DataOutputStream output = new DataOutputStream(new FileOutputStream(
				new File(filepath), append));
		output.write(packet);
		output.flush();
		output.close();
	}

	public void sendPacketToFlex(String subTopic, String clientId, Object obj) {
		MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
		AsyncMessage msg = new AsyncMessage();
		msg.setDestination("callTraceChannel");
		msg.setHeader("DSSubtopic", subTopic);
		msg.setClientId(clientId);
//		System.out.println("subTopic:"+subTopic);
		msg.setMessageId(UUIDUtils.createUUID());
		msg.setTimestamp(System.currentTimeMillis());
		msg.setBody(obj);
		messageBroker.routeMessageToService(msg, null);
	}
	
	public byte[] getCDRPacketFromFile(String fileName) throws IOException {
		FileInputStream in = null;
		File file = new File(fileName);
		int pos = 0;
		byte[] dataPacket = new byte[1024*10];
		byte[] filePacket = null;
		if (file.exists()) {
			// pcap文件头
			Pacp_file_header pcapfile = new Pacp_file_header();
			byte[] fileHeader = pcapfile.fileHeader();
			System.arraycopy(fileHeader, 0, dataPacket, 0, fileHeader.length);
			pos = fileHeader.length;
			File[] files = file.listFiles();
			Util.fileSort(files);
			for(int i=0; i<files.length; i++) {
				in = new FileInputStream(files[i]);
				byte[] data = new byte[(int)files[i].length()];
				in.read(data);
				byte[] packet = signallingPacket.TransformToDataPacket(data);
				System.arraycopy(packet, 0, dataPacket, pos, packet.length);
				pos = pos + packet.length;
				data = null;
				packet = null;
			}
			filePacket = new byte[pos];
			System.arraycopy(dataPacket, 0, filePacket, 0, pos);
			
		}
		return filePacket;
	}
/*	
	public void processPacketWithEndFlag(Command command) throws Exception {//针对含有结束标识符的cdr包的详细解码
		String key = command.getSvrId() + "" + command.getCdrId() + "" + command.getChar_protocol() + "" + command.getTs_s() + "" + command.getTs_ns();
		String filepath = pcapNativeFile + command.getSessionId() + fileSeparator + key;
		byte[] packet = getCDRPacketFromFile(filepath);
		String filename = pcapfilepath + fileSeparator + "detailed" + fileSeparator + command.getSessionId() + fileSeparator + key;
		File file = new File(filename);
		if (!file.exists())
			file.mkdirs();
		String pcapfile = filename + fileSeparator + command.getSequenceNo() + ".pcap";
		savePKTtoFile(pcapfile, packet, false);
		String tsharkcmd = tshark + " -r" + pcapfile + " " + pdml;
		signallingPacket.informationDecoding(tsharkcmd, pcapfile,
				cdrBean, packet, false, true);
	}
	*/
}
